#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <functional>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace LogModule;

const int defaultfd = -1;

class UdpSever
{
public:
    UdpSever(uint16_t port,std::function<std::string(const std::string&, InetAddr&)> func)
        : _sockfd(defaultfd), _port(port),_func(func)
    {
    }
    void Init()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }

        // 绑定socket信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);                  // 将端口号转为大端
        //local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 将ip转化为4字节，并将转化为网络序列
        local.sin_addr.s_addr = INADDR_ANY;//可以让客户端链接该服务器的任一ip地址，ip+指定的端口号
        // 对
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 1. 收消息, client为什么要个服务器发送消息啊？不就是让服务端处理数据。
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                InetAddr client(peer);
                buffer[s] = 0;
                // 收到的内容，当做英文单词
                std::string result = _func(buffer, client);


                // LOG(LogLevel::DEBUG) << "[" << peer_ip << ":" << peer_port<< "]# " << buffer; // 1. 消息内容 2. 谁发的？？

                // 2. 发消息
                // std::string echo_string = "server echo@ ";
                // echo_string += buffer;
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len);
            }
        }
    }
    ~UdpSever()
    {
        
    }

private:
   std::function<std::string(const std::string&, InetAddr&)> _func;
    // std::string _ip; 
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
};